import { login, logout, getInfo, updateProfile } from '@/api/user'
import { getPermissions } from '@/api/permission'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  email: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissionGrants: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSION_GRANTS: (state, permissionGrants) => {
    state.permissionGrants = permissionGrants
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      client_id,
      client_secret,
      grant_type,
      __tenant
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: password,
        client_id: client_id,
        client_secret: client_secret,
        grant_type: grant_type,
        __tenant: __tenant
      }).then(response => {
        const {
          data
        } = response
        commit('SET_TOKEN', data.access_token)
        setToken(data.access_token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const {
          data
        } = response

        if (!data) {
          reject('请重新登录.')
        }

        // const { roles, name, avatar, introduction } = data
        const roles = data.roles
        const name = data.name
        const avatar = data.avatar
        const email = data.email

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_EMAIL', email)
        // commit('SET_INTRODUCTION', introduction)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get permissions
  getPermissions({
    commit
  }, sub) {
    return new Promise((resolve, reject) => {
      var params = {}
      params.providerName = 'R'
      params.providerKey = 'admin'
      getPermissions(params).then(response => {
        const { data } = response
        const result = {}
        result.roles = []

        data.groups.forEach(element => {
          element.permissions.forEach(item => {
            result.roles.push(item.name)
          })
        })

        if (!result.roles || result.roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_PERMISSION_GRANTS', result.roles)
        resolve(result)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // reset avatar
  setAvatar({
    commit
  }, avatar) {
    return new Promise(resolve => {
      commit('SET_AVATAR', avatar)
    })
  },

  // update profile
  updateProfile({
    commit,
    state
  }, data) {
    return new Promise((resolve, reject) => {
      updateProfile(data).then(response => {
        const {
          data
        } = response

        if (!data) {
          reject('请重新登录')
        }

        const name = data.name
        const email = data.email

        commit('SET_NAME', name)
        commit('SET_EMAIL', email)

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  }
  // dynamically modify permissions
  // changeRoles({
  //   commit,
  //   dispatch
  // }, role) {
  //   return new Promise(async resolve => {
  //     const token = role + '-token'

  //     commit('SET_TOKEN', token)
  //     setToken(token)

  //     const {
  //       roles
  //     } = await dispatch('getInfo')

  //     resetRouter()

  //     // generate accessible routes map based on roles
  //     const accessRoutes = await dispatch('permission/generateRoutes', permissionGrants, {
  //       root: true
  //     })

  //     // dynamically add accessible routes
  //     router.addRoutes(accessRoutes)

  //     // reset visited views and cached views
  //     dispatch('tagsView/delAllViews', null, {
  //       root: true
  //     })

  //     resolve()
  //   })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
